import { createRouter, createWebHashHistory } from 'vue-router'
import pinia from '@/stores'
import { useUserStore } from '@/stores/userStore'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import stuRoute from './stu_route'
import domi_route from './domi_route'
import masterRoute from './admin_mastor_route'

// 登录界面路由
import LoginSystem from '@/views/login/LoginSystem.vue'
import AdminHome from '@/views/home/AdminHome.vue'
import RegistUser from '@/views/login/RegistUser.vue'

const userStore = useUserStore(pinia)

// 获取每个模块的路由名称
const stuRoutesName = stuRoute.reduce((pre, curr) => {
	pre.push(curr.name)
	return pre
}, [])

const domRoutesName = domi_route.reduce((pre, curr) => {
	pre.push(curr.name)
	return pre
}, [])
const adminRoutesName = masterRoute.reduce((pre, curr) => {
	pre.push(curr.name)
	return pre
}, [])

const router = createRouter({
	history: createWebHashHistory(),
	routes: [
		{
			path: '/login',
			name: 'login',
			component: LoginSystem,
		},
		{
			path: '/regist',
			name: 'regist',
			component: RegistUser,
		},
		{
			path: '/',
			redirect: '/login',
		},
		{
			path: '/home',
			name: 'Home',
			component: AdminHome,
			children: [...stuRoute, ...domi_route, ...masterRoute],
		},
	],
})

router.beforeEach((to, form, next) => {
	NProgress.start()
	let level = userStore.limts
	if (to.name == 'regist' || to.name === 'Home' || to.name === 'login') return next()
	if (!localStorage.getItem('token')) return next('/login')
	if (level == 3 && stuRoutesName.includes(to.name)) return next()
	else if (level == 1 && domRoutesName.includes(to.name)) return next()
	else if (level == 0 && adminRoutesName.includes(to.name)) return next()
	else next('/login')
})

router.afterEach((to, form) => {
	NProgress.done()
})

export default router
